package com.smartmedi.ai.controller;

import com.smartmedi.ai.common.BaseResponse;
import com.smartmedi.ai.common.ResultUtils;
import com.smartmedi.ai.service.RecordExtractionService;
import com.smartmedi.ai.utils.ChineseEncodingUtils;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/record")
@RequiredArgsConstructor
@Slf4j
public class RecordExtractionController {

    private final RecordExtractionService recordExtractionService;

    @PostMapping("/file")
    @Operation(summary = "处理上传的文本文件并修复中文编码问题")
    public BaseResponse<Object> processFile(@RequestParam("file") MultipartFile file) {
        try {
            // 使用ChineseEncodingUtils处理文件内容，自动修复可能的乱码问题
            byte[] fileBytes = file.getBytes();
            String content = ChineseEncodingUtils.bytesToString(fileBytes);
            // 进一步修复中文乱码
            content = ChineseEncodingUtils.fixGarbledText(content);
            
            log.info("文件处理完成，准备调用AI服务解析内容");
            
            // 调用接口实现病历解析转化为模板json
            Map<String, Object> result = recordExtractionService.processSingleStep(content);
            
            // 检查结果是否包含错误信息
            if (result.containsKey("code") && result.containsKey("success") && Boolean.FALSE.equals(result.get("success"))) {
                // 如果是错误响应，需要保持一致的响应格式
                int code = (int) result.get("code");
                String message = (String) result.get("message");
                return new BaseResponse<>(code, null, message);
            }
            
            return ResultUtils.success(result);
        } catch (IOException e) {
            log.error("文件处理异常", e);
            return new BaseResponse<>(50000, null, "文件处理失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("未知异常", e);
            return new BaseResponse<>(50000, null, "系统错误: " + e.getMessage());
        }
    }
}
